package com.example.demo.controller;

class ListNode{
    ListNode next;
    int val;
    ListNode(int val){
        this.val = val;
    }
}

class MyLinkedList {

    //[[],[1],[3],[1,2],[1],[1],[1]]
    //["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"]
    public static void main(String[] args) {
        MyLinkedList myLinkedList = new MyLinkedList();
        myLinkedList.addAtHead(1);
        myLinkedList.addAtTail(3);
        myLinkedList.addAtIndex(1,2);
        System.out.println(myLinkedList.get(1));
        myLinkedList.deleteAtIndex(1);
        System.out.println(myLinkedList.get(1));
    }

    int size;
    ListNode dummy;

    public MyLinkedList() {
        this.dummy = new ListNode(0);
        this.size = 0;
    }

    public int get(int index) {
        if(index < 0){
            return -1;
        }
        ListNode cur = this.dummy.next;
        int idx = 0;
        while(cur != null){
            if(idx == index){
                return cur.val;
            }
            cur = cur.next;
            idx++;
        }
        return -1;
    }

    public ListNode getNode(int index) {
        if(index < 0){
            return null;
        }
        ListNode cur = this.dummy.next;
        int idx = 0;
        while(cur != null){
            if(idx == index){
                return cur;
            }
            idx++;
        }
        return null;
    }

    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(size,val);
    }

    public void addAtIndex(int index, int val) {
        if(index < 0 || index > size){
            return;
        }
        ListNode cur = dummy;
        int idx = -1;
        while(cur != null){
            if(idx == index - 1){
                ListNode newNode = new ListNode(val);
                newNode.next = cur.next;
                cur.next = newNode;
            }
            idx++;
            cur = cur.next;
        }
        size++;
    }

    public void deleteAtIndex(int index) {
        if(index < 0 || index >= size){
            return;
        }
        ListNode cur = dummy;
        int idx = -1;
        while(cur != null){
            if(idx == index - 1){
                cur.next = cur.next.next;
            }
            idx++;
            cur = cur.next;
        }
        size--;
    }
}

/**
 * Your MyLinkedList object will be instantiated and called as such:
 * MyLinkedList obj = new MyLinkedList();
 * int param_1 = obj.get(index);
 * obj.addAtHead(val);
 * obj.addAtTail(val);
 * obj.addAtIndex(index,val);
 * obj.deleteAtIndex(index);
 */
